package com.itrip.log.module.handler;

import java.util.HashMap;
import java.util.Map;

import com.itrip.log.core.ReaderBean;

/**
 * Function:特定的日志记录入库
 *
 * @date:2016年10月14日/上午9:24:27
 * @Author:jeff@aoliday.cao
 * @version:1.0
 */
public abstract class MutilLineLogHandler extends AbstractHandler {

	private class MutilLineBean {
		StringBuffer lines = new StringBuffer();
		String lastFile;
		String host;
		String proc;;
		int lineCount;

		public MutilLineBean(String host, String proc, String lastFile) {
			this.lastFile = lastFile;
			this.host = host;
			this.proc = proc;
		}

	}

	private int lineCount = 50;
	private ThreadLocal<Map<String, MutilLineBean>> map = new ThreadLocal<Map<String, MutilLineBean>>();

	public void setLineCount(int lineCount) {
		this.lineCount = lineCount;
	}

	@Override
	public void handle(ReaderBean bean) {
		Map<String, MutilLineBean> mbeanMap = map.get();
		if (mbeanMap == null) {
			mbeanMap = new HashMap<String, MutilLineBean>();
			map.set(mbeanMap);
		}
		MutilLineBean mbean = mbeanMap.get(bean.getHost());
		if (mbean == null) {
			mbean = new MutilLineBean(bean.getHost(), bean.getProc(), bean.getFile());
			mbeanMap.put(bean.getHost(), mbean);
		}

		boolean fileChange = !mbean.lastFile.equals(bean.getFile());
		if (fileChange || mbean.lineCount > lineCount) {
			processLines(mbean.host, mbean.lastFile, mbean.proc, mbean.lines);
			mbean.lines = new StringBuffer(bean.getLine());
			mbean.lastFile = bean.getFile();
			mbean.host = bean.getHost();
			mbean.proc = bean.getProc();
			mbean.lineCount = 0;
		} else {
			mbean.lines.append(bean.getLine()).append(getLineConcater());
			mbean.lineCount++;
		}
	}

	/***
	 * 多行的连字符
	 * 
	 * @return
	 */
	public abstract String getLineConcater();

	/***
	 * 处理多行数据
	 * 
	 * @param host
	 * @param file
	 * @param proc
	 * @param lines
	 */
	public abstract void processLines(String host, String file, String proc, StringBuffer lines);

}
